﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EF;
using BL;
using BL.Entities;
using ApriBox.Mvc.UploadHelpers;

namespace ApriBox.Mvc.Controllers
{
    public class DeleteController : Controller
    {
        //
        // GET: /CreateFolder/




        FSEntitiesRepository repository = new FSEntitiesRepository();            
      

        private void FileDelete(int fileId)
        {
            string path = null;
            File f = repository.GetFileById(fileId);
            if (f != null)
            {
                path = f.PhysicalPath;
                repository.DecrementStorageCapacity(fileId, HttpContext.User.Identity.Name);
                repository.DeleteFile(fileId);

            }

            if (path != null || path != string.Empty)
            {

                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);
            }
            
        }

        private void FolderDelete(int folderId)
        {
            IEnumerable<File> files = repository.GetFiles(folderId);
            if (files != null)
            {
                foreach (var f in files)
                {
                    FileDelete(f.Id);
                }
            }
            IEnumerable<Folder> folders = repository.GetFolders(folderId);
            if (folders != null)
            {
                foreach (var fol in folders)
                {
                    if (fol != null)
                    {
                        FolderDelete(fol.Id);
                    }
                    repository.DeleteFolder(fol.Id);

                }
            }
            else
            {
                repository.DeleteFolder(folderId);
                return;
            }
            repository.DeleteFolder(folderId);
        }



        /*Удаление файлов*/

        [HttpPost]
        public void DeleteFile(int fileId, string cl)
        {
            if (cl == "deleteFile ui-selectee")
            {
                FileDelete(fileId);
            }
            else
            {
                FolderDelete(fileId);
            }

        }



    }
}
